const fs = require('fs');
const path = require('path');
var tools = require('../../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

var controller = require(tools.rootPath + 'libs/controller.js');
const functions = require(tools.appPath + 'functions');
const core_conf = require(tools.appPath + 'core_conf');
const core_enums = require(tools.appPath + 'core_enums');
var ejs = require('ejs');
module.exports = class extends controller {

  constructor() {
    super();
    //console.log('controller constructor');
    this.FORWARD = null;
    this.REQUEST_URI = null;
    this.TPL = null;
    this.req = null;
    this.res = null;
    this._session = {};
    this._template_var = {};
    this.MM = '';
    this.CC = '';
    this.AA = '';
    this.isPost = false;
    this.isGet = false;
  }

  async init() {
    this.REQUEST_URI = this.req.REQUEST_URI;
    this.TPL = this.req.TPL;
    this._session = this.req.session;
    this.MM = this.req.MM;
    this.CC = this.req.CC;
    this.AA = this.req.AA;
    this.isPost = this.req.isPost;
    this.isGet = this.req.isGet;

    this.SETTING = functions.load_setting(1);
    this.assign('SETTING', this.SETTING);

    let FORWARD = this.post('FORWARD');
    if (FORWARD) {
      this.FORWARD = encodeURI(FORWARD);
    } else {
      this.FORWARD = this.REQUEST_URI;
    }

    //other
    this.ip = this.req.headers['x-real-ip'];
    this.userAgent = this.req.headers["user-agent"];

    this.assign({
      MM: this.MM,
      CC: this.CC,
      AA: this.AA,
      FORWARD: this.FORWARD,
      REQUEST_URI: this.REQUEST_URI,
      VIEWROOT: tools.viewPath,
    });

    //core_conf
    this.CORE_CONF = new core_conf();
    this.CORE_ENUMS = core_enums;
    this.assign({
      CORE_CONF: this.CORE_CONF,
      CORE_ENUMS: this.CORE_ENUMS,
    });
    return true;
  }

  async __before() {
    return true;
  }

  msg(code, msg = '', url = '', data = []) {
    if (code === true) code = 1;
    if (code === false) code = 0;
    if (!this.isAjax()) {
      let html = '';
      if (code) {
        if (!msg) msg = '操作成功';
        let jump = `location.href='${url}';`;
        if (!url) jump = "window.history.back();";
        html = `<html><head><meta charset="utf-8"></head><body>加载中...<script>alert('${msg}');${jump}</script></body></html>`;
      } else {
        if (!msg) msg = '操作失败';
        html = `<html><head><meta charset="utf-8"></head><body>加载中...<script>alert('${msg}');window.history.back();</script></body></html>`;
      }
      return this.res.end(html);
    } else {
      if (code) {
        if (!msg) msg = '操作成功';
      } else {
        if (!msg) msg = '操作失败';
      }
      let d = {
        'code': code,
        'msg': msg,
        'url': url,
        'data': data,
      };
      return this.res.end(this.json(d));
    }
  }

  async session(name, val = '') {
    if (val === null) {
      delete this._session[name];
    }
    if (val === '') {
      return typeof (this._session[name]) != 'undefined' ? this._session[name] : null;
    }
    if (name && val) {
      this._session[name] = val;
    }
  }

  assign(obj, val = '') {
    if (typeof (obj) == 'string') {
      this._template_var[obj] = val;
    } else {
      Object.assign(this._template_var, obj);
    }
  }

  tpl(path = '', params = {}) {
    var f = path ? path : this.TPL;
    var str = fs.readFileSync(tools.viewPath + f + '.html', 'utf-8');
    let p = this._template_var;
    Object.assign(p, params);
    return ejs.render(str, p);
  }

  json(v) {
    return this.res.end(JSON.stringify(v));
  }

  redirect(url) {
    this.res.redirect(url);
  }

  post(key = '') {
    if (key) {
      return typeof (this.req.body[key]) != 'undefined' ? this.req.body[key] : null;
    }
    return typeof (this.req.body) != 'undefined' ? this.req.body : {};
  }

  get(key = '') {
    if (key) {
      return typeof (this.req.query[key]) != 'undefined' ? this.req.query[key] : null;
    }
    return typeof (this.req.query) != 'undefined' ? this.req.query : {};
  }

  isAjax() {
    return this.req.xhr;
  }

  referer() {
    return this.REQUEST_URI;
  }

  p(str) {
    console.log(str);
    this.res.end(str);
  }

  model(name) {
    var m = require(tools.modelPath + name + '.js');
    return new m();
  }

  async action(controller, action = undefined, path = '') {
    let c = require(path ? path + '/' + controller : tools.controllerPath + controller);
    let object = new c();
    object.req = this.req;
    object.res = this.res;
    await object.init();
    await object.__before();
    if (!action) return object;
    return await object[action](this.req, this.res);
  }

};
